import preferences from '@ohos.data.preferences';

let LOG_TAG = 'test log'

export class PreferencesUtil {
  prefMap: Map<String, preferences.Preferences> = new Map()

  // 这个加载应该在EntryAbility.ets就加载好了
  async load(context, name: string) {
    try {
      let pref = await preferences.getPreferences(context, name)
      this.prefMap.set(name, pref)
      console.log(LOG_TAG + `加载Preferences[${name}]成功`)
    } catch (e) {
      console.log(LOG_TAG + `加载Preferences[${name}]失败`, JSON.stringify(e))
    }
  }

  async putValue(name: string, key: string, value: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log(LOG_TAG + `Preferences[${name}]未初始化`)
      return
    } else {
      try {
        let pref = this.prefMap.get(name)
        // 写入数据
        await pref.put(key, value)
        // 刷新磁盘
        await pref.flush()
        console.log(LOG_TAG + `保存Preferences[${name}.${key} = ${value}成功`)
      } catch (e) {
        console.log(LOG_TAG + `保存Preferences[${name}.${key} = ${value}失败`)
      }
    }
  }

  async getValue(name: string, key: string, defaultValue: preferences.ValueType) {
    if (!this.prefMap.has(name)) {
      console.log(LOG_TAG + `Preferences[${name}]未初始化`)
      return null
    } else {
      try {
        let pref = this.prefMap.get(name)
        // 读取数据
        let value = await pref.get(key, defaultValue)
        console.log(LOG_TAG + `获取Preferences[${name}.${key}]成功`)
        return value
      } catch (e) {
        console.log(LOG_TAG + `获取Preferences[${name}.${key}]失败`)
        return null
      }
    }
  }

  async deleteValue(name: string, key: string) {
    if (!this.prefMap.has(name)) {
      console.info(LOG_TAG + `Preferences[${name}]未初始化`)
      return
    } else {
      let pref = this.prefMap.get(name)
      try {
        await pref.delete(key)
        console.info(LOG_TAG + `删除Preferences[${name}.${key}]成功`)
      } catch (e) {
        console.log(LOG_TAG + `删除Preferences[${name}.${key}]失败`)
      }
    }

  }
}

export default new PreferencesUtil()